/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 jfinal app. jfapp Group.
 */

package app.models.sys;

import app.Const;
import com.github.sog.annotation.TableBind;
import com.github.sog.kit.date.DateProvider;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.ehcache.CacheKit;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * <p>
 * The table ol_settings mapping model.
 * </p>
 */
@TableBind(tableName = "ol_settings")
public class Settings extends Model<Settings> {

    /**
     * The public dao.
     */
    public static final Settings dao = new Settings();

    public static final String VOTE_CURRENCY = "vote-currency";

    private static final long serialVersionUID = 1L;

    public static String getSettingVal(String item) {
        return CacheKit.get(Const.CACHE_SYSTEM_SETTING, item);
    }

    public static String vote() {
        return StringUtils.defaultIfEmpty(Settings.getSettingVal(Settings.VOTE_CURRENCY), "10");
    }

    public static void saveVote(String value) {
        CacheKit.put(Const.CACHE_SYSTEM_SETTING, VOTE_CURRENCY, value);
        Settings settings = Settings.dao.findbyName(VOTE_CURRENCY);
        if (settings == null) {
            settings = new Settings();
            settings.set("item", VOTE_CURRENCY);
            settings.set("item_val", value);
            settings.set("create_time", DateProvider.DEFAULT.getCurrentDate());
            settings.save();
        } else {
            settings.set("item_val", value);
            settings.update();
        }
    }

    private Settings findbyName(String voteCurrency) {
        return findFirst(SqlKit.sql("settings.findbyName"), voteCurrency);
    }

    public void initCache() {
        List<Settings> settingses = list();
        for (Settings settingse : settingses) {
            CacheKit.put(Const.CACHE_SYSTEM_SETTING, settingse.getStr("item"), settingse.getStr("item_val"));
        }
    }

    public List<Settings> list() {
        return find(SqlKit.sql("settings.list"));
    }
}